package copyengine.ui.tooltips
{
	import flash.display.DisplayObjectContainer;

	public final class CEToolTipsManger
	{
		private static var _instance:CEToolTipsManger;

		public static function get instance():CEToolTipsManger
		{
			if (_instance == null)
			{
				_instance = new CEToolTipsManger();
			}
			return _instance;
		}

		private var factory:ICEToolTipsFactory;
		private var tooltipsLayer:DisplayObjectContainer;

		private var allToolTipsWarpVector:Vector.<CEToolTipsWarp>;

		public function CEToolTipsManger()
		{
		}

		public function initialize(_tooltipsLayer:DisplayObjectContainer, _factory:ICEToolTipsFactory):void
		{
			tooltipsLayer = _tooltipsLayer;
			factory = _factory;
			allToolTipsWarpVector = new Vector.<CEToolTipsWarp>();
		}

		public function register(_source:ICETooltipsSource, _type:*):void
		{
			findAndRemovePriorTips(_source)
			var warp:CEToolTipsWarp = new CEToolTipsWarp();
			var toolTips:ICEToolTips = factory.createToolTips(_source, _type);

			tooltipsLayer.addChild(toolTips.getContainer());

			warp.initialize(_source, toolTips, tooltipsLayer.stage);

			allToolTipsWarpVector.push(warp);
		}

		public function unRegister(_source:ICETooltipsSource):void
		{
			for (var i:int = 0; i < allToolTipsWarpVector.length; i++)
			{
				if (_source == allToolTipsWarpVector[i].getSource())
				{
					allToolTipsWarpVector[i].dispose();
					allToolTipsWarpVector.splice(i, 1);
					break;
				}
			}
		}

		/**
		 *清除掉所有的TooltipsWarp，发生在场景切换时候
		 */
		public function cleanAll():void
		{
			if (allToolTipsWarpVector)
			{
				while (allToolTipsWarpVector.length > 0)
				{
					allToolTipsWarpVector.pop().dispose();
				}
			}
		}

		private function findAndRemovePriorTips(_source:ICETooltipsSource):void
		{
			for (var i:int = 0; i < allToolTipsWarpVector.length; i++)
			{
				var warp:CEToolTipsWarp = allToolTipsWarpVector[i];
				if (warp.getSource().isEqual(_source))
				{
					unRegister(warp.getSource());
					break;
				}
			}
		}

	}
}
